package com.lw.leetcode.arr.a;

import java.util.HashMap;
import java.util.Map;

/**
 * 697. 数组的度
 *
 * @Author liw
 * @Date 2021/6/16 20:47
 * @Version 1.0
 */
public class FindShortestSubArray {

    public static void main(String[] args){
        FindShortestSubArray test = new FindShortestSubArray();
        int[] arr = {1};
        int shortestSubArray = test.findShortestSubArray(arr);
        System.out.println(shortestSubArray);
    }

    public int findShortestSubArray(int[] nums) {
        Map<Integer, int[]> map = new HashMap<>();

        int min = 0;
        int length = nums.length;
        for (int i = 0; i < length; i++) {
            int num = nums[i];
            int[] arr = map.get(num);
            if (arr == null) {
                map.put(num, new int[]{1, i, i});
            } else {
                arr[2] = i;
                arr[0] += 1;
            }
        }
        int maxValue = -1;
        for (Map.Entry<Integer, int[]> entry : map.entrySet()) {
            int[] arr = entry.getValue();
            if (arr[0] > maxValue) {
                maxValue = arr[0];
                min = arr[2] - arr[1];
            } else if (arr[0] == maxValue && arr[2] - arr[1] < min) {
                min = arr[2] - arr[1];
            }
        }
        return min + 1;
    }
}
